package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author slstart
 * @create 2021-05-23 17:47
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserService();

    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User u = new User();
        u.setUsername(username);
        u.setPassword(password);
        User user = userService.login(u);

        if (user == null) {
            request.setAttribute("msg", "账号或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {
            //登录成功
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            String oldUri = (String) session.getAttribute("oldUri");
            if(oldUri != null){
                response.sendRedirect(oldUri);
            }else{

                request.getRequestDispatcher(request.getContextPath()+"/login.jsp").forward(request, response);
            }

        }
    }
}
